package kr.co.happenstance;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import com.nostra13.universalimageloader.core.ImageLoader;

import kr.co.happenstance.lib.MatchingLib;
import kr.co.happenstance.lib.vo.LibResultVo;
import kr.co.happenstance.lib.vo.MatchingInfoResultVo;
import kr.co.happenstance.util.Util;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class PushMeetActivity extends BaseActivity implements View.OnClickListener{
	protected final String TAG = "<<<PushMeetActivity>>>";
	
	/**
	 * 대기 시간을 갖고 있는 Calendar 객체 
	 */
	private Calendar waitingDate;
	
	/**
	 * push 받은 매칭요청테이블 시퀀
	 */
	private int matchingRequestSeq;
	
	private WaitingTimerHandler waitingTimerHandler = null;
	
	
	/**
	 * 요청자 Profile 이미지 ImageView 객체  
	 */
	private ImageView ivPushProfile;
	
	/**
	 * 요청자와의 거리 TextView 객체 
	 */
	private TextView tvDistance;
	
	/**
	 * 약속시간 TextView 객체 
	 */
	private TextView tvPromiseDate;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_push_meet);		
		init(this, C.MENU_ID_PUSH_MEET);
		
		matchingRequestSeq = getIntent().getIntExtra("matchingRequestSeq", -1);
		
		ivPushProfile = (ImageView) this.findViewById(R.id.iv_push_profile);
		tvDistance = (TextView) this.findViewById(R.id.tv_distance);
		tvPromiseDate = (TextView) this.findViewById(R.id.tv_promise_date);
		
			
		//요청 정보 가져오기 
		new MatchingRequestInfoTask().execute();
		
		
	}
	
	@Override
	protected void onPause(){
		super.onPause();
		Log.d(TAG, "onPause().............");
		if(waitingTimerHandler != null){
			waitingTimerHandler.removeMessages(0);
		}	
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		Log.d(TAG, "onResume().............");
		if(waitingTimerHandler != null){
			waitingTimerHandler.sendEmptyMessage(0);
		}
	}
	
	@Override
	protected void onDestroy(){
		super.onDestroy();
		Log.d(TAG, "onDestory().............");
		if(waitingTimerHandler != null){
			waitingTimerHandler.removeMessages(0);
			Log.d(TAG, "");
		}	
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.btn_push_accept:
				Log.d(TAG, "btn_push_accept onClick......................");
				if(waitingDate.getTimeInMillis() - Calendar.getInstance().getTimeInMillis() < 0){
					//수락 대기시간 종료
					showExpireWaitingDate();
				}else{
					new AcceptTask().execute();
				}
				
				
			break;
		}
	}	
	
	/**
	 * 수락 대기 시간이 초과 되었음을 보여주는 메소드 
	 */
	private void showExpireWaitingDate(){
		new CustomAlertDialogBuilder(this)
		.setTitle(this.getString(R.string.alert_title))
		.setMessage(getString(R.string.alert_msg_expire_waiting))
		.setCancelable(false)
		.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				dialog.dismiss();
				//PushMeetActivity.this.finish();
				
			}
		})
		.create();				
	}
	
	
	/**
	 * 매칭 정보 가져오는 Task 클래스
	 * 
	 * @author Administrator
	 *
	 */
	private class MatchingRequestInfoTask extends AsyncTask<Void, Void, LibResultVo> {
		@Override
		protected void onPreExecute() {
			showProgress();
		}
		@Override
		protected LibResultVo doInBackground(Void... arg0) {
			MatchingInfoResultVo resultVo = null;
			try{
				MatchingLib lib = new MatchingLib();
				
				//현재 매칭 정보 확인 플래그 변경
				lib.matchingUpdate(myApp.id, matchingRequestSeq, C.MATCH_UPDATE_GBN_RECEIPIENT_CONFIRM);
				
				//매칭 정보 가져오기
				resultVo = (MatchingInfoResultVo) lib.matchingRequestInfo(matchingRequestSeq, Double.toString(myLocation.getLatitude()), Double.toString(myLocation.getLongitude()));
				
			}catch(Exception e){
				e.printStackTrace();
				resultVo = null;
			}
			return resultVo;
		}
		
		@Override
		protected void onPostExecute(LibResultVo resultVo) {
			closeProgress();
			MatchingInfoResultVo vo = (MatchingInfoResultVo) resultVo;
			if(vo == null || vo.getResult().equals(C.API_RESULT_VALUE_FAIL)){
				Log.d(TAG, "MatchingInfoResultVo null......");
				new CustomAlertDialogBuilder(PushMeetActivity.this, R.string.alert_title, R.string.alert_msg_exception).create();
				PushMeetActivity.this.finish();
				
			}else{
				
				//대기시간
				waitingDate = Util.getCalendar(vo.getWaitingDate());
				
				//현재시간
				Calendar cal = Calendar.getInstance();
				
				if(waitingDate.getTimeInMillis() - cal.getTimeInMillis() < 0){
					//대기시간 초과
					showExpireWaitingDate();
				}else{
				
					//프로필 이미지 셋
					if(vo.getProfileYn().equals("Y")){
						String profileUrl = C.FACEBOOK_PROIFILE_URL+vo.getId()+"/picture?type=large";
						Log.d(TAG, "profileUrl["+profileUrl+"]");
						ImageLoader.getInstance().displayImage(profileUrl, ivPushProfile);
					}
					
					//거리(km -> m 단위로)
					String distance = Double.toString(vo.getDistance() * 1000);
					tvDistance.setText(distance + "M");
					
					//약속시간 
					SimpleDateFormat formatter = new SimpleDateFormat("a hh:mm", Locale.ENGLISH);
					tvPromiseDate.setText(formatter.format(Util.getCalendar(vo.getPromiseDate()).getTime()));
					
					waitingTimerHandler = new WaitingTimerHandler(PushMeetActivity.this);
					waitingTimerHandler.sendEmptyMessage(0);
				}
			}
			
		}
		
	}

	
	/**
	 * 만나자 요청 수락 Task 클래스 
	 * 
	 * @author namjungyeob
	 *
	 */
	private class AcceptTask extends AsyncTask<Void, Void, LibResultVo> {
		@Override
		protected void onPreExecute() {
			showProgress();
		}
		
		@Override
		protected LibResultVo doInBackground(Void... params) {
			LibResultVo result = null;
			try{
				result = new MatchingLib().matchingUpdate(myApp.id, matchingRequestSeq, C.MATCH_UPDATE_GBN_RECIPIENT_ACCEPT);
			}catch(Exception e){
				e.printStackTrace();
			}
			return result;
		}
		
		@Override
		protected void onPostExecute(LibResultVo resultVo) {
			closeProgress();
			
			if(resultVo == null || resultVo.getResult().equals(C.API_RESULT_VALUE_FAIL)){
				Log.d(TAG, "LibResultVo null......");
				new CustomAlertDialogBuilder(PushMeetActivity.this, R.string.alert_title, R.string.alert_msg_exception).create();
			}else{
				Intent intent = new Intent(PushMeetActivity.this, WaitingRecipientActivity.class);
				intent.putExtra("matchingRequestSeq", matchingRequestSeq);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				PushMeetActivity.this.startActivity(intent);
				
			}	
			
		}	
		
	}
	/**
	 * 대기시간 Timer 핸들러
	 * 
	 * @author Administrator
	 *
	 */
	private static class WaitingTimerHandler extends Handler{
		boolean finish;
		PushMeetActivity activity;
		
		WaitingTimerHandler(PushMeetActivity activity){
			this.activity = activity;
		}
		public void handleMessage(Message msg){
			if(activity.waitingDate.getTimeInMillis() - Calendar.getInstance().getTimeInMillis() < 0  && !finish){
				//대기시간 초과시
				finish = true;
				this.removeMessages(0);
				activity.showExpireWaitingDate();
			}else{
				this.sendEmptyMessageDelayed(0,1000);
			}
		}		
	}
		
}
